#include "CTaskProviders.h"

CTaskProviders* CTaskProviders::m_instance = 0;
CTaskProviders* CTaskProviders::instance()
{
	if(m_instance == 0)
		m_instance = new CTaskProviders();
		
	return m_instance;
}

CTaskProviders::CTaskProviders()
{
}

bool CTaskProviders::loadProviders()
{
	// Clear list
	m_providers.clear();
		
	// Browser plugin directory to find plugins files
	QDir pluginsDir = QDir(qApp->applicationDirPath());
	pluginsDir.cd("taskproviders");
	
	foreach (QString fileName, pluginsDir.entryList(QDir::Files))
	{
		QPluginLoader loader(pluginsDir.absoluteFilePath(fileName));
		QObject *plugin = loader.instance();
		
		if(plugin)
			tryAddProvider(plugin);
		else
			qDebug() << loader.errorString();
	}
	
	if(m_providers.size() > 0)
		return true;
	else
		return false;
}

void CTaskProviders::tryAddProvider(QObject *plugin)
{
	ITaskProvider* iTaskProv = qobject_cast<ITaskProvider*>(plugin);
	if(iTaskProv)
		m_providers.push_back(iTaskProv);
}

ITaskProvider* CTaskProviders::taskProvider(int id)
{
	if((0 <= id) && (id < m_providers.size()))
		return m_providers.at(id);
	else
		return 0;
}

ITaskProvider* CTaskProviders::taskProvider(QString taskProviderName)
{
	for(int i = 0; i < m_providers.size(); i++)
	{
		if(m_providers.at(i)->providerName() == taskProviderName)
			return m_providers.at(i);
	}

	return 0;
}

QVector<ITaskProvider*> CTaskProviders::taskProviders()
{
	return m_providers;
}

QStringList CTaskProviders::availableTaskProvider()
{
	QStringList listtp;
	foreach(ITaskProvider* tp, m_providers)
		listtp << tp->providerName();
		
	return listtp;
}
